<template>
  <!-- 目前使用的 -->
  <div class="real_time_box">
    <!-- <dv-border-box-12 style="height: 100%" :class="'echarts_box'">
      <div
        style="height: 100%"
        class="chart flex-x flex-center"
        ref="chart"
      ></div>
      <div v-if="!lineChart" class="h-full w100 flex-x flex-center no_data">
        暂无数据
      </div>
    </dv-border-box-12> -->
    <!-- 全屏 -->
    <transition name="el-fade-in-linear">
      <!-- v-if="fullscreen" -->
      <dv-border-box-12
        ref="box12ref"
        style="height: 100%"
        :class="fullscreen ? 'fixed_echarts' : 'echarts_box'"
      >
        <!-- class="fixed_echarts" -->
        <div
          v-if="isShowChart"
          :key="'chart_1'"
          style="height: 100%"
          class="chart w100"
          ref="chart"
          id="chart"
        ></div>
        <div class="flex-x flex-center no_data w100" v-else>
          暂无数据
        </div>
      </dv-border-box-12>
    </transition>
  </div>
</template>

<script>
import { formatDate } from "@/filter/index";
let that = null;
import { mixinReszie } from "@/mixin/resize.js";
import { LINE_COLOES } from "../../../js/utils";
import { generateId } from "@/utils";
import { mapGetters } from "vuex";
import { restSql } from "@/api/taos";
export default {
  mixins: [mixinReszie],
  computed: {
    isShowChart() {
      if (!this.option.series.length) {
        return false;
      }
      return this.option.series.some(item => item.data.length !== 0);
    },
    ...mapGetters([
      "deviceAttributesList",
      "realTimeData",
      "controlDeviceInfo"
    ]),
    _chartKeys() {
      return this.controlDeviceInfo._chartKeys;
    }
  },
  props: {
    brder1Key: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      dataZoomId: "",
      zoomStart: 0,
      zoomEnd: 100,
      lineChart: null,
      fullscreen: false,
      // brder1Key: generateId(),
      series: [],
      option: {
        title: {
          text: "实时工艺曲线",
          x: "center",
          top: "10px",
          textStyle: {
            color: "#fff",
            fontSize: 18,
            fontWeight: "400"
          }
        },
        dataZoom: [
          {
            show: true,
            height: 25,
            xAxisIndex: [0],
            bottom: 15,
            start: 0,
            end: 100,
            handleSize: "110%"
          },
          {
            type: "inside",
            show: true,
            height: 15,
            start: 1,
            end: 35
          }
        ],
        color: LINE_COLOES,
        tooltip: {
          formatter: params => {
            var str = "";
            for (var i = 0, l = params.length; i < l; i++) {
              // 小圆点
              const bgStr = `<span style='margin-right: 6px;display:inline-block;width:10px;height:10px;border-radius:10px;background-color:${params[i].color};'></span>`;
              let value = params[i].value;
              if (!value && String(value) !== 0) {
                value = "--";
              }

              str +=
                bgStr +
                params[i].seriesName +
                ": " +
                value +
                this.deviceAttributesList.find(
                  item => item.name == params[i].seriesName
                )?.unit +
                "<br />";
            }
            return params[0].axisValue + "<br />" + str;
          },
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#fff"
            },
            lineStyle: {
              type: "dashed"
            }
          }
        },
        grid: {
          left: "25",
          right: "25",
          bottom: "44",

          top: "65",
          containLabel: true
        },
        legend: {
          data: [],
          padding: [14, 0, 0, 0],
          orient: "horizontal",
          //   icon: "rect",
          show: true,
          textStyle: {
            color: "#fff"
          },
          left: 20,
          top: 25
        },
        xAxis: {
          type: "category",
          data: [],
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: "#fff",
            fontSize: 12
            // textStyle: {

            // },
          },
          axisLine: {
            show: false
          }
        },
        yAxis: [],
        series: []
      }
    };
  },
  watch: {
    "$store.state.app.sidebar.opened"(val, oldVal) {
      setTimeout(() => {
        this.$nextTick(() => {
          this.$refs.box12ref.initWH();
        });
      }, 300);
    },
    // brder1Key(val, oldVal) {
    //   console.log("val, oldVal :>> ", val, oldVal);
    //   console.log("4 :>> ", 4);
    // },
    // 接收实时数据
    realTimeData: {
      handler: function(newData, oldData) {
        if (JSON.stringify(newData) !== "{}") {
          this.setOption(newData);
        }
      }
      // deep: true,
      // immediate: true
    },
    // 历史数据
    deviceAttributesList: {
      handler: function(newData, oldData) {
        if (newData.length) {
          console.log("监听历史曲线 :>> ", newData);
          setTimeout(() => {
            if (this.lineChart) {
              this.lineChart.dispose();
              this.lineChart = null;
              // this.brder1Key = generateId();
            }
            this.init();
          }, 500);
        }
      }
      // deep: true,
      // immediate: true
    }
  },
  created() {
    that = this;
  },
  methods: {
    // 生成Y轴
    renderyAxis(name, offset) {
      return {
        position: "left",
        offset: offset,
        type: "value",
        name,
        nameTextStyle: {
          color: "#fff"
        },
        axisLabel: {
          textStyle: {
            color: "#fff",
            fontSize: 12
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: "#fff"
          }
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        }
      };
    },
    init() {
      this.series = [];
      if (!this.deviceAttributesList.length) {
        if (this.lineChart) {
          this.lineChart.dispose();
          this.lineChart = null;
        }
        return;
      }
      const yAxisData = [];
      let offset = 0;
      this.deviceAttributesList.forEach(item => {
        // 设置y轴 单位
        if (!yAxisData.find(y => y.name == item.unit)) {
          yAxisData.push(this.renderyAxis(item.unit, offset));
          offset += 38;
        }
      });
      this.option = {
        ...this.option,
        title: {
          text: "实时工艺曲线",
          x: "center",
          top: "10px",
          textStyle: {
            color: "#fff",
            fontSize: 18,
            fontWeight: "400"
          }
        },
        dataZoom: this.deviceAttributesList.length
          ? [
              {
                id: "dataZoomY",
                show: this.deviceAttributesList.length,
                height: 25,
                xAxisIndex: [0],
                bottom: 15,
                start: this.zoomStart,
                end: this.zoomEnd,
                handleSize: "110%"
              },
              {
                id: "dataZoomX",
                type: "inside",
                show: this.deviceAttributesList.length,
                height: 15,
                start: 1,
                end: 100
              }
            ]
          : [],
        color: LINE_COLOES,
        toolbox: {
          // 工具栏
          itemSize: 16,
          showTitle: true,
          right: 24,
          top: "10px",
          feature: {
            myTool: {
              //自定义工具 myTool
              show: true,
              title: that.fullscreen ? "取消全屏" : "全屏显示",
              color: "#fff",

              iconStyle: {
                borderColor: "#fff"
              },
              icon: that.fullscreen
                ? "M298.666667 631.466667H226.133333v-81.066667h217.6v204.8h-85.333333v-68.266667l-128 128L170.666667 759.466667l128-128z m422.4 0l128 128-59.733334 59.733333-128-128v68.266667h-85.333333V554.666667h217.6v81.066666h-72.533333zM298.666667 341.333333L187.733333 230.4 243.2 170.666667l115.2 115.2V217.6h85.333333v204.8H226.133333V341.333333H298.666667z m430.933333 0h64v81.066667h-217.6V217.6h85.333333v72.533333L780.8 170.666667l59.733333 59.733333L729.6 341.333333z"
                : "path://M919.920093 725.414549q3.014188 26.122962 7.033105 58.776664t7.53547 66.814498 7.53547 67.819227 7.033105 60.786122q6.028376 47.222277-41.193901 44.208089-25.118232-2.009459-56.767205-5.526011t-64.805039-7.53547-65.809769-8.037834-59.781393-7.033105q-29.137149-3.014188-37.174984-16.578033t9.042564-30.644243q11.052022-10.047293 27.127691-27.630056t27.127691-28.634785q11.052022-12.056752 7.033105-22.104044t-16.075669-23.108774q-28.13242-27.127691-51.241194-49.231735t-51.241194-51.241194q-6.028376-6.028376-12.056752-13.061481t-9.042564-15.573304-1.004729-18.085127 13.061481-20.59695q6.028376-6.028376 10.047293-10.549658t8.037834-8.037834 8.540199-8.037834 11.554387-12.559116q20.094586-20.094586 37.174984-17.080398t37.174984 23.108774 41.193901 40.691536 47.222277 46.719912q19.089857 18.085127 32.653702 25.118232t26.625326-6.028376q9.042564-9.042564 22.606409-21.60168t23.611138-22.606409q17.080398-17.080398 30.644243-13.061481t16.578033 30.141879zM43.79615 383.80659q-3.014188-26.122962-7.033105-58.776664t-7.53547-66.814498-7.53547-67.819227-7.033105-60.786122q-3.014188-26.122962 6.53074-36.170255t33.658431-8.037834q25.118232 2.009459 56.767205 5.526011t64.805039 7.53547 65.809769 8.037834 59.781393 7.033105q30.141879 3.014188 37.677348 16.578033t-9.544928 30.644243q-10.047293 10.047293-24.615868 26.122962t-25.620597 27.127691q-12.056752 12.056752-8.037834 22.104044t17.080398 23.108774q13.061481 14.06621 24.615868 24.615868t22.606409 21.099315 23.108774 22.606409l25.118232 25.118232q6.028376 6.028376 11.554387 14.06621t8.037834 17.080398-0.502365 19.089857-13.061481 20.094586l-11.052022 11.052022q-4.018917 4.018917-7.53547 8.037834t-8.540199 8.037834l-11.052022 12.056752q-20.094586 20.094586-34.663161 15.070939t-34.663161-25.118232-38.179713-37.677348-44.208089-43.705724q-18.085127-18.085127-32.151337-25.118232t-27.127691 6.028376q-9.042564 10.047293-25.118232 24.615868t-26.122962 24.615868q-17.080398 17.080398-30.141879 13.061481t-16.075669-30.141879zM905.853883 84.397261q26.122962-3.014188 36.170255 6.53074t8.037834 34.663161-5.526011 56.767205-7.53547 64.805039-8.037834 65.809769-7.033105 59.781393q-3.014188 29.137149-16.578033 37.174984t-30.644243-10.047293q-10.047293-10.047293-26.122962-24.615868t-27.127691-25.620597q-12.056752-11.052022-22.104044-7.53547t-23.108774 16.578033q-27.127691 27.127691-47.724641 49.231735t-48.729371 50.236465q-6.028376 6.028376-14.06621 11.554387t-17.080398 8.037834-19.089857-0.502365-20.094586-14.06621q-6.028376-6.028376-10.549658-10.047293t-8.540199-8.037834-8.540199-8.037834-11.554387-12.056752q-20.094586-20.094586-16.075669-35.165525t25.118232-35.165525l38.179713-40.189172q19.089857-20.094586 45.212818-46.217547 19.089857-18.085127 26.122962-32.151337t-7.033105-26.122962q-9.042564-9.042564-23.108774-24.615868t-24.113503-25.620597q-17.080398-17.080398-13.061481-30.141879t30.141879-16.075669 58.776664-7.033105 67.316863-7.53547 67.819227-7.53547 60.283758-7.033105zM350.238584 640.012559q6.028376 6.028376 10.549658 10.047293t8.540199 8.037834l8.037834 9.042564 12.056752 11.052022q20.094586 20.094586 17.582763 36.672619t-23.611138 37.677348q-19.089857 19.089857-40.189172 40.691536t-47.222277 47.724641q-18.085127 18.085127-22.606409 29.639514t8.540199 24.615868q10.047293 9.042564 22.606409 22.606409t22.606409 23.611138q17.080398 17.080398 12.559116 30.141879t-30.644243 16.075669-58.274299 7.033105-66.814498 8.037834-68.321592 8.037834-60.786122 7.033105q-25.118232 2.009459-35.66789-7.53547t-8.540199-33.658431q2.009459-25.118232 5.526011-56.767205t7.53547-64.805039 8.037834-65.809769 7.033105-59.781393q3.014188-30.141879 16.578033-37.677348t30.644243 9.544928q10.047293 10.047293 27.630056 26.122962t28.634785 27.127691q12.056752 12.056752 20.094586 10.549658t20.094586-14.568575q13.061481-13.061481 25.118232-25.620597t24.113503-24.615868 24.615868-25.118232 26.625326-27.127691q6.028376-6.028376 13.061481-12.056752t15.573304-9.042564 18.085127-0.502365 20.59695 13.563845z",
              onclick: function() {
                //生成全屏显示的图表
                that.fullscreen = !that.fullscreen;
                // that.init();
                // that.brder1Key = generateId();
                if (that.lineChart) {
                  that.lineChart.dispose();
                  that.lineChart = null;
                }
                setTimeout(() => {
                  that.lineChart = that.$echarts.init(that.$refs.chart);
                  that.lineChart.setOption(that.option);
                  that.$refs.box12ref.initWH();
                }, 300);
                that.$emit("checkFull", that.option, that.fullscreen);
              }
            }
          }
        },

        grid: {
          // left: "25",
          // right: "25",
          bottom: that.fullscreen ? "50" : "44",

          top: "85",
          containLabel: true
        },
        legend: {
          data: this.deviceAttributesList.map(item => item.name),
          padding: [14, 0, 0, 0],
          orient: "horizontal",
          //   icon: "rect",
          show: true,
          textStyle: {
            color: "#fff"
          },
          left: 20,
          top: 25
        },
        xAxis: {
          type: "category",
          data: this.deviceAttributesList[0].times,
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: "#fff",
            fontSize: 12,
            formatter: timeVal => {
              return formatDate(timeVal, "HH:mm:ss");
            }
            // textStyle: {
            // },
          },
          axisLine: {
            show: false
          }
        },
        yAxis: yAxisData,
        series: this.deviceAttributesList.map(item => {
          return {
            name: item.name,
            type: "line",
            smooth: true,
            showSymbol: false,
            data: item.data,
            yAxisIndex: yAxisData.findIndex(y => y.name == item.unit)
          };
        })
      };
      console.log(" 历史数据最终拼接的option :>> ", this.option);
      this.setOption();
    },
    setOption(request) {
      this.$nextTick(() => {
        if (request) {
          const { eventDate, metadata } = request;
          // this.$moment(eventDate).format("YYYY-MM-DD HH:mm:ss")
          this.option.xAxis.data.push(formatDate(eventDate));
          this.deviceAttributesList.forEach(item => {
            if (metadata[item.token]) {
              // console.log("this._chartKeys :>> ", metadata);
              const isSite = this.option.series.find(f => f.name == item.name);
              if (isSite) {
                isSite.data.push(metadata[item.token]);
              } else {
                // 判断当前是否有y轴
                const yAxisIndex = this.option.yAxis.findIndex(
                  y => y.name === item.unit
                );
                // 不存在y轴就添加一条
                if (yAxisIndex == -1) {
                  this.option.yAxis.push(
                    this.renderyAxis(item.unit, this.option.yAxis.length * 38)
                  );
                }
                this.option.series.push({
                  name: item.name,
                  type: "line",
                  smooth: true,
                  showSymbol: false,
                  data: [metadata[item.token]],
                  yAxisIndex: this.option.yAxis.findIndex(
                    y => y.name == item.unit
                  )
                });
              }
            }
          });

          this.option.legend.data = this.option.series.map(item => item.name);
        }

        if (!document.getElementById("chart")) return;
        if (!this.lineChart) {
          this.lineChart = this.$echarts.init(document.getElementById("chart"));
          // this.chartKey = generateId();
          this.resize();
        }
        if (this.dataZoomId == "dataZoomX") {
          this.option.dataZoom[1].start = this.zoomStart;
          this.option.dataZoom[1].end = this.zoomEnd;
        }
        if (this.dataZoomId == "dataZoomY") {
          this.option.dataZoom[0].start = this.zoomStart;
          this.option.dataZoom[0].end = this.zoomEnd;
        }

        this.lineChart.on("dataZoom", function(event) {
          that.dataZoomId = event.dataZoomId;
          if (event.batch) {
            that.zoomStart = event.batch[0].start;
            that.zoomEnd = event.batch[0].end;
          } else {
            that.zoomStart = event.start;
            that.zoomEnd = event.end;
          }
        });
        // console.log("this.option :>> ", this.option);
        const xTimes = this.option.xAxis.data;
        if (xTimes.length) {
          // 8小时的数组长度
          const s8 = 8 * 60 * 60;
          const s = xTimes.length;
          console.log("相差 28800 :>> ", s, s8);
          // if (s > s8) {
          //   this.option.xAxis.data.splice(0, 1);
          //   this.option.series.forEach(item => {
          //     item.data.splice(0, 1);
          //   });
          // }
        }

        this.lineChart.setOption(this.option);
      });
    }
  },
  mounted() {
    // this.init();
  },
  destroyed() {}
};
</script>

<style scoped lang="scss">
.real_time_box {
  // position: relative;
  .no_data {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
  }
}
.echarts_box {
  .chart {
    width: 100%;
    /* height: 260px; */
  }
}
.fixed_echarts {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  width: 100% !important;
  height: 100% !important;
  background: url(../../../../../assets/images/applicationCenter/app_bg.jpg)
    no-repeat 100%;
  background-size: cover;
}
</style>
